package com.example.skillcinema.ui.screens.search

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import androidx.constraintlayout.widget.ConstraintLayout
import com.example.skillcinema.adapters.YearPickerRecyclerViewAdapter
import com.example.skillcinema.databinding.CustomYearPickerBinding
import java.time.LocalDate

class CustomYearPicker(context: Context, attrs: AttributeSet?) : ConstraintLayout(context, attrs) {
    private var _binding: CustomYearPickerBinding? =
        CustomYearPickerBinding.inflate(LayoutInflater.from(context), this, true)
    private val binding: CustomYearPickerBinding
        get() = _binding!!

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        _binding = null
    }

    private var currentYear = LocalDate.now().year
    var selectedYear: Int = currentYear
    private val adapter: YearPickerRecyclerViewAdapter =
        YearPickerRecyclerViewAdapter { onYearClicked(it) }

    private fun onYearClicked(year: Int) {
        selectedYear = year
    }

    init {
        binding.yearRecyclerView.adapter = adapter
        updateListData()
        binding.prevPageButton.setOnClickListener { changePage(-1) }
        binding.nextPageButton.setOnClickListener { changePage(1) }
    }

    fun changePage(multiplyer: Int) {
        currentYear += (multiplyer * YEAR_RANGE)
        updateListData()

    }

    private fun updateListData() {
        binding.rangeTextView.text = "$currentYear - ${currentYear + YEAR_RANGE}"
        adapter.setData((currentYear..currentYear + 11).toList())
    }


    companion object {
        const val YEAR_RANGE = 11
    }
}